package cn.bingo.yunsj.service;

import cn.bingo.yunsj.common.StateCode;
import cn.bingo.yunsj.common.exception.EmException;
import cn.bingo.yunsj.common.exception.OwnException;
import cn.bingo.yunsj.common.result.Response;
import cn.bingo.yunsj.controller.model.SerachModel;
import cn.bingo.yunsj.domain.RpNotSend;
import cn.bingo.yunsj.domain.RpSendFail;
import cn.bingo.yunsj.domain.RpSuccess;
import cn.bingo.yunsj.mail.model.MailModel;
import cn.bingo.yunsj.mapper.RpNotSendMapper;
import cn.bingo.yunsj.mapper.RpSendFailMapper;
import cn.bingo.yunsj.utils.DateUtils;
import org.springframework.beans.CachedIntrospectionResults;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.mail.MessagingException;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
public class FailService {

    @Autowired
    private RpSendFailMapper rpSendFailMapper;

    @Autowired
    private MailService mailService;

    public Response search(SerachModel serachModel, String start, String end) {
        if(serachModel.getUserModel()==null){
            serachModel.setUserModel("");
        }

        List<RpSendFail> list = rpSendFailMapper.search(serachModel.getUserModel(), start, end);
        return new Response(StateCode.SEARCH_SUCCESS, (long) list.size(),list);
    }

    //消息单个补发
    @Transactional
    public Response replacement(String sendId, MailModel mailModel){

        // 理论上还需要判断三天内得才能补发
        Long between_days = DateUtils.between_days(rpSendFailMapper.selectByPrimaryKey(sendId).getSendTime());

        if(between_days>3){
            throw new OwnException(EmException.REP_FAIL);
        }

        //邮件发送
        mailService.sendMail(mailModel);

        //删除未发送表数据
        rpSendFailMapper.deleteByPrimaryKey(sendId);

        return new Response(StateCode.REPLACEMENT_SUCCESS);
    }

    // 获取所有人漏发信息
    public Response all() {
        List<RpSendFail> rpSendFails = rpSendFailMapper.selectAll();
        return new Response(StateCode.SEARCH_SUCCESS, (long) rpSendFails.size(),rpSendFails);
    }

    public Response getName() {
        List<RpSendFail> list = rpSendFailMapper.selectName();
        return new Response(StateCode.SEARCH_SUCCESS, (long) list.size(),list);
    }
}
